###Copied from SolidWaste_Spillover.R

library(ggmap)
library(rgdal)
library(rgeos)
library(maptools)
library(dplyr)
library(tidyr)
library(tmap)
library(ri)
library(spdep)
library(sp)
library(readr)

lc1 <- readOGR(dsn="/Users/mbuntaine/Google Drive/Kampala Solid Waste project/LC1 Shapefiles", 
               layer="Kampala_villagesfff")


#######Finding contiguous polygons#######
#http://stackoverflow.com/questions/26499010/finding-adjacent-polygons-in-r-neighbors

lc1 <- readOGR(dsn="/Users/mbuntaine/Google Drive/Kampala Solid Waste project/LC1 Shapefiles", 
               layer="Kampala_villagesfff")

see <- gTouches(lc1, byid=TRUE)

nb <- poly2nb(lc1)
mat <- nb2mat(nb, style="B")
colnames(mat) <- rownames(mat)


#######Generating contiguity variable for each unit (Phase 1)#######

#Step 1. Take drawn sample as given
p1.sample <- read_csv("~/Google Drive/Kampala Solid Waste project/LC1 Shapefiles/FinalExperimentalSample_CorrectedJune2016.csv")

#Step 2. Create matrix of contiguous zones
lc1 <- readOGR(dsn="/Users/mbuntaine/Google Drive/Kampala Solid Waste project/LC1 Shapefiles", 
               layer="Kampala_villagesfff")
nb <- poly2nb(lc1)
mat <- nb2mat(nb, style="B")
colnames(mat) <- rownames(mat)

#Step 3. Create list of zones with/without contiguities
all.list <- p1.sample$X1
con.test <- rep(NA, length(all.list))

for (i in 1:length(all.list)){
  row.test <- mat[all.list[i]==as.numeric(row.names(mat)),]==1
  con.zones <- (0:754)[row.test]
  con.test[i] <- sum(con.zones %in% all.list)>0
}

spill.dta <- data.frame(all.list, p1.sample$VNAME, p1.sample$Parishes, p1.sample$assignment, con.test)
names(spill.dta) <- c("X1","Vname","parish","assignment","con.test")
spill.dta$assignment <- as.character(spill.dta$assignment)
spill.dta$loc.id <- tolower(paste(spill.dta$Vname,spill.dta$parish,sep="."))
#Note: zone i.mbuya ii has non-uniform, duplicated treatment assignment
spill.dta$assignment.realized <- ifelse(spill.dta$loc.id=="zone i.mbuya ii","mixed",spill.dta$assignment)
